<template>
  <div class="parent-home-container">
    <!-- 作业紧急提醒 -->
    <el-alert
      v-if="hasUrgentHomework"
      title="有作业即将截止，请提醒孩子！"
      type="warning"
      closable
      style="margin-bottom: 20px;"
    />

    <!-- 欢迎区域 -->
    <el-card class="welcome-card" shadow="never">
      <div class="welcome-content">
        <h2>欢迎回来，{{ user.name }}家长！</h2>
        <p>您正在查看 {{ childInfo.name }}（{{ childInfo.grade }}）的学习情况</p>
      </div>
    </el-card>

    <!-- 孩子状态统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="8">
        <el-card class="stat-card" shadow="hover" @click="openAllHomeworkDialog">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: rgba(255, 152, 0, 0.1);">
              <el-icon color="#FF9800"><Notebook /></el-icon>
            </div>
            <div class="stat-data">
              <p class="stat-title">未完成作业</p>
              <p class="stat-value">{{ childStats.unfinishedHomework }}</p>
              <p class="stat-desc">比上周减少1项</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card" shadow="hover" @click="navigateTo('grades')">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: rgba(103, 194, 58, 0.1);">
              <el-icon color="#67C23A"><Star /></el-icon>
            </div>
            <div class="stat-data">
              <p class="stat-title">最近测验成绩</p>
              <p class="stat-value">{{ childStats.recentScore }}<span class="stat-unit">分</span></p>
              <p class="stat-desc">班级排名前20%</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card" shadow="hover" @click="openAllNoticesDialog">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: rgba(64, 158, 255, 0.1);">
              <el-icon color="#409EFF"><Bell /></el-icon>
            </div>
            <div class="stat-data">
              <p class="stat-title">未读通知</p>
              <p class="stat-value">{{ childStats.unreadNotifications }}</p>
              <p class="stat-desc">2条紧急通知</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 教师通知区域 -->
    <el-card class="section-card" shadow="never">
      <template #header>
        <div class="section-header">
          <h3 class="section-title">最新教师通知</h3>
          <el-button type="text" @click="openAllNoticesDialog">
            查看全部 <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
      </template>
      <el-timeline>
        <el-timeline-item 
          v-for="(notice, index) in recentNotices" 
          :key="notice.id"
          :timestamp="notice.time"
          :hollow="index === 0"
          :color="index === 0 ? '#00B4A0' : ''"
          placement="top"
        >
          <el-card shadow="hover" class="notice-card" @click="openNoticeDetailDialog(notice)">
            <div class="notice-header">
              <h4 class="notice-title">{{ notice.title }}</h4>
              <el-tag v-if="notice.urgent" type="danger" size="small">紧急</el-tag>
            </div>
            <p class="notice-content">{{ truncateText(notice.content, 80) }}</p>
            <div class="notice-footer">
              <span class="notice-sender">{{ notice.teacherName }}</span>
              <el-button 
                type="text" 
                size="small" 
                @click.stop="openNoticeDetailDialog(notice)"
              >
                查看详情
              </el-button>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>

    <!-- 作业进度 -->
    <el-card class="section-card" shadow="never">
      <template #header>
        <div class="section-header">
          <h3 class="section-title">作业完成情况</h3>
          <!-- 作业查看全部：改为打开弹窗 -->
          <el-button type="text" @click="openAllHomeworkDialog">
            查看全部 <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
      </template>
      <el-table 
        :data="homeworkList" 
        style="width: 100%"
        :header-cell-style="{background: '#f8fafc', color: '#64748b'}"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="subject" label="科目" width="120">
          <template #default="scope">
            <el-tag :type="getSubjectTagType(scope.row.subject)" effect="plain">
              {{ scope.row.subject }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="作业名称" min-width="200">
          <template #default="scope">
            <span class="homework-title" @click="openHomeworkDetailDialog(scope.row)">
              {{ scope.row.title }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="deadline" label="截止时间" width="150">
          <template #default="scope">
            <span :class="{'deadline-near': isDeadlineNear(scope.row.deadline)}">
              {{ scope.row.deadline }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === '已完成' ? 'success' : 'warning'" 
              :effect="scope.row.status === '已完成' ? 'dark' : 'light'"
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status !== '已完成'"
              type="text" 
              size="small" 
              @click="remindHomework(scope.row.id)"
            >
              提醒完成
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 通知详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="通知详情"
      :width="isMobile ? '90%' : '600px'"
      :close-on-click-modal="false"
    >
      <div v-if="currentNotice" class="dialog-detail-content">
        <div class="detail-header">
          <h3 class="detail-title">{{ currentNotice.title }}</h3>
          <el-tag v-if="currentNotice.urgent" type="danger" size="small">紧急</el-tag>
        </div>
        <div class="detail-meta">
          <span class="meta-item">
            <el-icon color="#94a3b8" size="14"><User /></el-icon>
            {{ currentNotice.teacherName }}
          </span>
          <span class="meta-item">
            <el-icon color="#94a3b8" size="14"><Clock /></el-icon>
            {{ currentNotice.time }}
          </span>
        </div>
        <div class="detail-body">
          <p>{{ currentNotice.content }}</p>
        </div>
        <div v-if="!currentNotice.read" class="read-tag">
          <el-tag type="info" size="small">未读</el-tag>
          <el-button 
            type="text" 
            size="small" 
            @click="markAsRead(currentNotice.id)"
            class="mark-read-btn"
          >
            标记为已读
          </el-button>
        </div>
      </div>
      <div v-else class="dialog-loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        <p>加载中...</p>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 全部通知弹窗 -->
    <el-dialog
      v-model="allNoticesDialogVisible"
      title="全部教师通知"
      :width="isMobile ? '90%' : '800px'"
      :close-on-click-modal="false"
    >
      <div class="dialog-search-bar">
        <el-input
          v-model="noticeSearch"
          placeholder="搜索通知标题/内容"
          size="small"
          :prefix-icon="Search"
          class="search-input"
        />
        <el-select
          v-model="noticeFilter"
          placeholder="筛选状态"
          size="small"
          class="filter-select"
        >
          <el-option label="全部通知" value="all"></el-option>
          <el-option label="未读通知" value="unread"></el-option>
          <el-option label="紧急通知" value="urgent"></el-option>
        </el-select>
      </div>
      <div class="all-notices-list">
        <el-timeline v-if="filteredNotices.length > 0">
          <el-timeline-item 
            v-for="(notice, index) in paginatedNotices" 
            :key="notice.id"
            :timestamp="notice.time"
            :color="notice.urgent ? '#f56c6c' : (index === 0 ? '#00B4A0' : '#409EFF')"
            placement="top"
          >
            <el-card 
              shadow="hover" 
              class="all-notice-item"
              @click="openNoticeDetailDialog(notice)"
            >
              <div class="all-notice-header">
                <h4 class="all-notice-title">
                  {{ notice.title }}
                  <el-tag v-if="notice.urgent" type="danger" size="small" class="urgent-tag">紧急</el-tag>
                  <el-tag v-if="!notice.read" type="info" size="small" class="unread-tag">未读</el-tag>
                </h4>
              </div>
              <p class="all-notice-content">{{ truncateText(notice.content, 80) }}</p>
              <div class="all-notice-footer">
                <span class="all-notice-sender">{{ notice.teacherName }}</span>
                <el-button 
                  type="text" 
                  size="small" 
                  @click.stop="openNoticeDetailDialog(notice)"
                >
                  查看详情
                </el-button>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        <div v-else class="all-notices-empty">
          <el-icon size="48" color="#94a3b8"><ChatLineSquare /></el-icon>
          <p>暂无匹配的通知</p>
        </div>
      </div>
      <div class="dialog-pagination" v-if="filteredNotices.length > 0">
        <el-pagination
          @size-change="handleNoticePageSizeChange"
          @current-change="handleNoticeCurrentPageChange"
          :current-page="noticeCurrentPage"
          :page-sizes="[5, 10, 15]"
          :page-size="noticePageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredNotices.length"
          small
        ></el-pagination>
      </div>
      <template #footer>
        <el-button @click="allNoticesDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增：全部作业弹窗 -->
    <el-dialog
      v-model="allHomeworkDialogVisible"
      title="全部作业情况"
      :width="isMobile ? '90%' : '1000px'"
      :close-on-click-modal="false"
      :max-height="isMobile ? '80vh' : '70vh'"
    >
      <!-- 作业筛选栏 -->
      <div class="dialog-search-bar homework-search-bar">
        <el-input
          v-model="homeworkSearch"
          placeholder="搜索作业名称/科目"
          size="small"
          :prefix-icon="Search"
          class="search-input"
        />
        <el-select
          v-model="homeworkStatusFilter"
          placeholder="筛选状态"
          size="small"
          class="filter-select"
        >
          <el-option label="全部作业" value="all"></el-option>
          <el-option label="已完成" value="已完成"></el-option>
          <el-option label="未完成" value="未完成"></el-option>
        </el-select>
        <el-select
          v-model="homeworkSubjectFilter"
          placeholder="筛选科目"
          size="small"
          class="filter-select"
        >
          <el-option label="全部科目" value="all"></el-option>
          <el-option label="语文" value="语文"></el-option>
          <el-option label="数学" value="数学"></el-option>
          <el-option label="英语" value="英语"></el-option>
          <el-option label="科学" value="科学"></el-option>
          <el-option label="其他" value="其他"></el-option>
        </el-select>
      </div>

      <!-- 作业统计概览 -->
      <div class="homework-stats">
        <el-row :gutter="16" class="stats-row-mini">
          <el-col :span="6" v-for="(stat, key) in homeworkStats" :key="key">
            <div class="homework-stat-item">
              <p class="stat-label">{{ stat.label }}</p>
              <p class="stat-count">{{ stat.value }}</p>
              <p class="stat-tip" :class="stat.tipClass">{{ stat.tip }}</p>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 全部作业列表 -->
      <div class="all-homework-list">
        <el-table 
          v-if="filteredHomework.length > 0"
          :data="paginatedHomework" 
          style="width: 100%"
          :header-cell-style="{background: '#f8fafc', color: '#64748b'}"
          :row-class-name="tableRowClassName"
          border
          size="small"
        >
          <el-table-column prop="subject" label="科目" width="100">
            <template #default="scope">
              <el-tag :type="getSubjectTagType(scope.row.subject)" effect="plain" size="small">
                {{ scope.row.subject }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="作业名称" min-width="220">
            <template #default="scope">
              <span class="homework-title" @click="openHomeworkDetailDialog(scope.row)">
                {{ scope.row.title }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="作业要求" min-width="250">
            <template #default="scope">
              <p class="homework-desc">{{ truncateText(scope.row.description, 60) }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="assignTime" label="布置时间" width="140">
            <template #default="scope">
              <span>{{ scope.row.assignTime }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="deadline" label="截止时间" width="140">
            <template #default="scope">
              <span :class="{'deadline-near': isDeadlineNear(scope.row.deadline)}">
                {{ scope.row.deadline }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="110">
            <template #default="scope">
              <el-tag 
                :type="scope.row.status === '已完成' ? 'success' : 'warning'" 
                :effect="scope.row.status === '已完成' ? 'dark' : 'light'"
                size="small"
              >
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="提交时间" width="140">
            <template #default="scope">
              <span v-if="scope.row.status === '已完成'">{{ scope.row.submitTime || '未提交' }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template #default="scope">
              <el-button 
                type="text" 
                size="small" 
                @click="openHomeworkDetailDialog(scope.row)"
                class="operate-btn"
              >
                查看详情
              </el-button>
              <el-button 
                v-if="scope.row.status !== '已完成'"
                type="text" 
                size="small" 
                @click="remindHomework(scope.row.id)"
                class="operate-btn remind-btn"
              >
                提醒完成
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 作业空状态 -->
        <div v-else class="all-homework-empty">
          <el-icon size="48" color="#94a3b8"><Document /></el-icon>
          <p>暂无匹配的作业记录</p>
        </div>
      </div>

      <!-- 作业分页 -->
      <div class="dialog-pagination" v-if="filteredHomework.length > 0">
        <el-pagination
          @size-change="handleHomeworkPageSizeChange"
          @current-change="handleHomeworkCurrentPageChange"
          :current-page="homeworkCurrentPage"
          :page-sizes="[8, 15, 20]"
          :page-size="homeworkPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredHomework.length"
          small
        ></el-pagination>
      </div>

      <template #footer>
        <el-button @click="allHomeworkDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增：作业详情弹窗 -->
    <el-dialog
      v-model="homeworkDetailDialogVisible"
      title="作业详情"
      :width="isMobile ? '90%' : '700px'"
      :close-on-click-modal="false"
    >
      <div v-if="currentHomework" class="homework-detail-content">
        <!-- 作业基本信息 -->
        <div class="homework-base-info">
          <div class="info-header">
            <h3 class="homework-detail-title">{{ currentHomework.title }}</h3>
            <el-tag 
              :type="getSubjectTagType(currentHomework.subject)" 
              effect="plain"
              class="subject-tag"
            >
              {{ currentHomework.subject }}
            </el-tag>
          </div>

          <div class="info-meta">
            <div class="meta-item">
              <el-icon color="#94a3b8" size="14"><Calendar /></el-icon>
              <span class="meta-label">布置时间：</span>
              <span class="meta-value">{{ currentHomework.assignTime }}</span>
            </div>
            <div class="meta-item">
              <el-icon color="#94a3b8" size="14"><Clock /></el-icon>
              <span class="meta-label">截止时间：</span>
              <span 
                class="meta-value" 
                :class="{'deadline-near': isDeadlineNear(currentHomework.deadline)}"
              >
                {{ currentHomework.deadline }}
                <span v-if="isDeadlineNear(currentHomework.deadline)" class="urgent-tip">（即将截止）</span>
              </span>
            </div>
            <div class="meta-item">
              <el-icon color="#94a3b8" size="14"><User /></el-icon>
              <span class="meta-label">布置老师：</span>
              <span class="meta-value">{{ currentHomework.teacherName }}</span>
            </div>
            <div class="meta-item">
              <el-icon color="#94a3b8" size="14"><CircleCheck /></el-icon>
              <span class="meta-label">完成状态：</span>
              <el-tag 
                :type="currentHomework.status === '已完成' ? 'success' : 'warning'" 
                :effect="currentHomework.status === '已完成' ? 'dark' : 'light'"
                class="status-tag"
              >
                {{ currentHomework.status }}
              </el-tag>
              <span v-if="currentHomework.status === '已完成'" class="submit-time">
                （提交时间：{{ currentHomework.submitTime }}）
              </span>
            </div>
          </div>
        </div>

        <!-- 作业要求 -->
        <div class="homework-requirement">
          <h4 class="detail-section-title">作业要求</h4>
          <div class="requirement-content">
            <p>{{ currentHomework.description }}</p>
          </div>
        </div>

        <!-- 作业附件 -->
        <div v-if="currentHomework.attachments && currentHomework.attachments.length > 0" class="homework-attachments">
          <h4 class="detail-section-title">相关附件</h4>
          <div class="attachment-list">
            <div v-for="(file, idx) in currentHomework.attachments" :key="idx" class="attachment-item">
              <el-link :href="file.url" target="_blank" class="file-link">
                <el-icon class="file-icon"><Document /></el-icon>
                <span class="file-name">{{ file.name }}</span>
                <span class="file-size">({{ formatFileSize(file.size) }})</span>
              </el-link>
            </div>
          </div>
        </div>

        <!-- 提交情况（已完成时显示） -->
        <div v-if="currentHomework.status === '已完成'" class="homework-submission">
          <h4 class="detail-section-title">提交情况</h4>
          <div class="submission-content">
            <p class="submission-desc">孩子已按时提交作业，老师批改意见将在1-2个工作日内反馈</p>
            <div v-if="currentHomework.submissionFiles && currentHomework.submissionFiles.length > 0" class="submission-files">
              <h5 class="files-title">提交文件：</h5>
              <div class="submission-file-list">
                <div v-for="(file, idx) in currentHomework.submissionFiles" :key="idx" class="submission-file-item">
                  <el-link :href="file.url" target="_blank" class="file-link">
                    <el-icon class="file-icon"><Document /></el-icon>
                    <span class="file-name">{{ file.name }}</span>
                    <span class="file-size">({{ formatFileSize(file.size) }})</span>
                  </el-link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 作业加载状态 -->
      <div v-else class="dialog-loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        <p>加载中...</p>
      </div>

      <!-- 作业详情弹窗底部操作 -->
      <template #footer>
        <el-button 
          v-if="currentHomework && currentHomework.status !== '已完成'"
          type="primary" 
          @click="remindHomework(currentHomework.id)"
        >
          提醒孩子完成
        </el-button>
        <el-button @click="homeworkDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Notebook,
  Star,
  Bell,
  ArrowRight,
  User,
  Clock,
  Search,
  ChatLineSquare,
  Loading,
  Calendar,
  CircleCheck,
  Document,
  CircleCheckFilled
} from '@element-plus/icons-vue'

// 路由与状态管理
const router = useRouter()

// 用户信息（模拟数据）
const user = ref({
  name: '王小明',
  role: '家长'
})

// ---------------------- 弹窗控制变量 ----------------------
// 通知相关弹窗
const detailDialogVisible = ref(false)
const currentNotice = ref(null)
const allNoticesDialogVisible = ref(false)
const noticeSearch = ref('')
const noticeFilter = ref('all')
const noticeCurrentPage = ref(1)
const noticePageSize = ref(5)

// 新增：作业相关弹窗
const allHomeworkDialogVisible = ref(false)
const homeworkDetailDialogVisible = ref(false)
const currentHomework = ref(null)
// 作业筛选与分页
const homeworkSearch = ref('')
const homeworkStatusFilter = ref('all')
const homeworkSubjectFilter = ref('all')
const homeworkCurrentPage = ref(1)
const homeworkPageSize = ref(8)

// 响应式判断
const isMobile = ref(false)

// ---------------------- 数据模拟 ----------------------
const childInfo = ref({
  name: '王小明',
  grade: '三年级(2)班',
  studentId: '2021030201'
})

const childStats = ref({
  unfinishedHomework: 2,
  recentScore: 92,
  unreadNotifications: 3
})

// 通知数据
const allNotices = ref([
  {
    id: 1,
    title: '关于下周数学单元测验的通知',
    content: '下周三将进行数学第三单元测验，请督促孩子复习相关知识点，特别是分数运算部分。建议每天完成10道计算题练习，巩固基础。',
    time: '2023-10-15 09:30',
    teacherName: '李老师（数学）',
    urgent: true,
    read: false
  },
  {
    id: 2,
    title: '家长会安排通知',
    content: '本月25日晚上7点将召开线上家长会，会议内容包括学期教学计划和学生表现反馈，请提前安排时间参加。会议链接将在24日发送至班级群，请留意群消息。',
    time: '2023-10-14 16:45',
    teacherName: '张老师（班主任）',
    urgent: false,
    read: false
  },
  {
    id: 3,
    title: '课外阅读推荐',
    content: '本学期推荐阅读书目已更新，包含《夏洛的网》《长袜子皮皮》等经典儿童文学作品，建议家长陪同阅读，每周至少完成1篇亲子阅读记录。',
    time: '2023-10-12 10:15',
    teacherName: '王老师（语文）',
    urgent: false,
    read: true
  },
  {
    id: 4,
    title: '秋季运动会报名通知',
    content: '11月5日将举办秋季运动会，包含跑步、跳远、跳绳等项目，有意向报名的同学请于10月20日前提交报名表，家长可协助孩子选择合适的项目。',
    time: '2023-10-10 14:20',
    teacherName: '刘老师（体育）',
    urgent: false,
    read: true
  },
  {
    id: 5,
    title: '疫苗接种提醒',
    content: '学校将于10月20日组织流感疫苗接种，请家长填写接种同意书并于10月18日前交回班主任处，如有过敏史请提前告知。',
    time: '2023-10-08 09:10',
    teacherName: '张老师（班主任）',
    urgent: true,
    read: false
  },
  {
    id: 6,
    title: '数学作业更正提醒',
    content: '上周数学练习册P38-39页错误较多的同学，请督促孩子重新更正，明天上课将进行讲解，确保掌握相关知识点。',
    time: '2023-10-05 16:30',
    teacherName: '李老师（数学）',
    urgent: false,
    read: true
  }
])

const recentNotices = computed(() => allNotices.value.slice(0, 3))

// 扩展：作业数据（新增更多字段和数据）
const allHomework = ref([
  {
    id: 1,
    subject: '语文',
    title: '第三单元生字抄写（每个字写5遍）',
    description: '1. 抄写第三单元课后生字表中所有生字，每个字写5遍；2. 给每个生字组2个词语；3. 背诵生字对应的课文段落；4. 完成练习册P32页生字填空。',
    assignTime: '2023-10-14',
    deadline: '2023-10-16',
    status: '已完成',
    submitTime: '2023-10-15 18:30',
    teacherName: '王老师（语文）',
    attachments: [
      { name: '第三单元生字表.pdf', url: '#', size: 1245000 },
      { name: '生字练习范例.docx', url: '#', size: 890000 }
    ],
    submissionFiles: [
      { name: '王小明-语文生字作业.jpg', url: '#', size: 2350000 }
    ]
  },
  {
    id: 2,
    subject: '数学',
    title: '练习册P45-46页应用题',
    description: '1. 独立完成练习册P45-46页所有应用题（共12道）；2. 要求写出详细解题步骤，不能只写答案；3. 用铅笔书写，保持卷面整洁；4. 家长可协助孩子理解题意，但不可直接告知答案。',
    assignTime: '2023-10-15',
    deadline: '2023-10-17',
    status: '未完成',
    submitTime: '',
    teacherName: '李老师（数学）',
    attachments: [
      { name: '应用题解题思路指导.pdf', url: '#', size: 980000 }
    ],
    submissionFiles: []
  },
  {
    id: 3,
    subject: '英语',
    title: '背诵Unit3课文并录音上传',
    description: '1. 熟练背诵Unit3 "My School" 全文；2. 使用英语APP录音上传（时长不超过3分钟）；3. 注意发音准确，语调自然；4. 录音前先朗读3遍，确保流畅度。',
    assignTime: '2023-10-14',
    deadline: '2023-10-16',
    status: '未完成',
    submitTime: '',
    teacherName: '陈老师（英语）',
    attachments: [
      { name: 'Unit3课文音频.mp3', url: '#', size: 3500000 },
      { name: '课文重点句型总结.docx', url: '#', size: 760000 }
    ],
    submissionFiles: []
  },
  {
    id: 4,
    subject: '科学',
    title: '完成植物生长观察报告',
    description: '1. 观察家中或学校种植的植物，记录生长情况（高度、叶片数量、颜色变化）；2. 绘制植物生长曲线图；3. 撰写200字左右观察报告，描述观察发现；4. 附上植物当前照片（1-2张）。',
    assignTime: '2023-10-12',
    deadline: '2023-10-18',
    status: '已完成',
    submitTime: '2023-10-17 10:15',
    teacherName: '赵老师（科学）',
    attachments: [
      { name: '观察报告模板.xlsx', url: '#', size: 1120000 }
    ],
    submissionFiles: [
      { name: '王小明-植物观察报告.xlsx', url: '#', size: 1850000 },
      { name: '植物照片.jpg', url: '#', size: 2100000 }
    ]
  },
  {
    id: 5,
    subject: '美术',
    title: '我的家庭肖像画',
    description: '1. 用彩铅或水彩绘制家庭肖像（包含至少2位家庭成员）；2. 注意人物面部特征和服装细节；3. 画面要有背景（如客厅、阳台等）；4. 在画作背面写上作品名称和创作思路（50字左右）。',
    assignTime: '2023-10-15',
    deadline: '2023-10-19',
    status: '已完成',
    submitTime: '2023-10-18 16:40',
    teacherName: '林老师（美术）',
    attachments: [
      { name: '肖像画创作技巧.pdf', url: '#', size: 2300000 }
    ],
    submissionFiles: [
      { name: '我的家庭肖像画.jpg', url: '#', size: 3200000 }
    ]
  },
  {
    id: 6,
    subject: '数学',
    title: '口算练习（100道）',
    description: '1. 完成100道口算题（加减乘除混合）；2. 计时完成，记录所用时间；3. 正确率要求达到95%以上；4. 错误题目用红笔更正，并重新计算3遍。',
    assignTime: '2023-10-16',
    deadline: '2023-10-18',
    status: '未完成',
    submitTime: '',
    teacherName: '李老师（数学）',
    attachments: [
      { name: '口算练习题.pdf', url: '#', size: 650000 }
    ],
    submissionFiles: []
  },
  {
    id: 7,
    subject: '语文',
    title: '《秋天的雨》读后感',
    description: '1. 阅读课文《秋天的雨》，撰写300字左右读后感；2. 结合自己的生活经历，谈谈对秋天的感受；3. 要求语句通顺，表达真情实感；4. 用方格稿纸书写，字迹工整。',
    assignTime: '2023-10-16',
    deadline: '2023-10-19',
    status: '未完成',
    submitTime: '',
    teacherName: '王老师（语文）',
    attachments: [
      { name: '《秋天的雨》课文原文.docx', url: '#', size: 480000 },
      { name: '读后感写作指导.pdf', url: '#', size: 820000 }
    ],
    submissionFiles: []
  },
  {
    id: 8,
    subject: '英语',
    title: '制作英语单词卡片',
    description: '1. 制作Unit3-4单元重点单词卡片（共20个单词）；2. 卡片正面写英文单词，背面写中文意思和例句；3. 卡片尺寸不小于10cm×15cm，可装饰美化；4. 下周一带到学校进行展示。',
    assignTime: '2023-10-15',
    deadline: '2023-10-20',
    status: '已完成',
    submitTime: '2023-10-18 19:25',
    teacherName: '陈老师（英语）',
    attachments: [
      { name: '单词列表.xlsx', url: '#', size: 350000 }
    ],
    submissionFiles: [
      { name: '单词卡片照片.jpg', url: '#', size: 2800000 }
    ]
  }
])

// 首页作业列表（取前4条）
const homeworkList = computed(() => allHomework.value.slice(0, 4))

// ---------------------- 计算属性 ----------------------
// 紧急作业提醒
const hasUrgentHomework = computed(() => {
  return homeworkList.value.some(item => 
    item.status === '未完成' && isDeadlineNear(item.deadline)
  )
})

// 通知筛选与分页
const filteredNotices = computed(() => {
  return allNotices.value.filter(notice => {
    const matchSearch = notice.title.includes(noticeSearch.value) || 
                       notice.content.includes(noticeSearch.value)
    const matchFilter = noticeFilter.value === 'all' 
      ? true 
      : (noticeFilter.value === 'unread' ? !notice.read : notice.urgent)
    return matchSearch && matchFilter
  })
})

const paginatedNotices = computed(() => {
  const startIndex = (noticeCurrentPage.value - 1) * noticePageSize.value
  return filteredNotices.value.slice(startIndex, startIndex + noticePageSize.value)
})

// 新增：作业筛选与分页
const filteredHomework = computed(() => {
  return allHomework.value.filter(homework => {
    // 搜索筛选（名称/科目）
    const matchSearch = homework.title.includes(homeworkSearch.value) || 
                       homework.subject.includes(homeworkSearch.value)
    // 状态筛选
    const matchStatus = homeworkStatusFilter.value === 'all' 
      ? true 
      : homework.status === homeworkStatusFilter.value
    // 科目筛选
    const matchSubject = homeworkSubjectFilter.value === 'all' 
      ? true 
      : homework.subject === homeworkSubjectFilter.value
    return matchSearch && matchStatus && matchSubject
  })
})

const paginatedHomework = computed(() => {
  const startIndex = (homeworkCurrentPage.value - 1) * homeworkPageSize.value
  return filteredHomework.value.slice(startIndex, startIndex + homeworkPageSize.value)
})

// 新增：作业统计数据
const homeworkStats = computed(() => {
  const total = allHomework.value.length
  const completed = allHomework.value.filter(item => item.status === '已完成').length
  const unfinished = allHomework.value.filter(item => item.status === '未完成').length
  const urgent = allHomework.value.filter(item => item.status === '未完成' && isDeadlineNear(item.deadline)).length
  
  return {
    total: {
      label: '全部作业',
      value: total,
      tip: '本月累计',
      tipClass: 'normal-tip'
    },
    completed: {
      label: '已完成',
      value: completed,
      tip: `完成率 ${Math.round((completed/total)*100)}%`,
      tipClass: 'success-tip'
    },
    unfinished: {
      label: '未完成',
      value: unfinished,
      tip: '需尽快完成',
      tipClass: 'warning-tip'
    },
    urgent: {
      label: '即将截止',
      value: urgent,
      tip: '2天内截止',
      tipClass: 'danger-tip'
    }
  }
})

// ---------------------- 生命周期 ----------------------
onMounted(() => {
  handleResize()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// ---------------------- 方法 ----------------------
// 导航方法（仅保留成绩页面跳转）
const navigateTo = (path) => {
  console.log(`导航到: ${path}`)
  // 若后续需要跳转成绩页面，可添加 router.push(`/parent/${path}`)
}

// ---------------------- 通知相关方法 ----------------------
const openNoticeDetailDialog = (notice) => {
  currentNotice.value = { ...notice }
  detailDialogVisible.value = true
  if (!notice.read) {
    markAsRead(notice.id)
  }
}

const markAsRead = (noticeId) => {
  const noticeIndex = allNotices.value.findIndex(item => item.id === noticeId)
  if (noticeIndex !== -1) {
    allNotices.value[noticeIndex].read = true
    const recentIndex = recentNotices.value.findIndex(item => item.id === noticeId)
    if (recentIndex !== -1) {
      recentNotices.value[recentIndex].read = true
    }
    childStats.value.unreadNotifications = allNotices.value.filter(item => !item.read).length
  }
}

const openAllNoticesDialog = () => {
  allNoticesDialogVisible.value = true
  noticeSearch.value = ''
  noticeFilter.value = 'all'
  noticeCurrentPage.value = 1
}

const handleNoticePageSizeChange = (size) => {
  noticePageSize.value = size
  noticeCurrentPage.value = 1
}

const handleNoticeCurrentPageChange = (page) => {
  noticeCurrentPage.value = page
}

// ---------------------- 新增：作业相关方法 ----------------------
// 打开全部作业弹窗
const openAllHomeworkDialog = () => {
  allHomeworkDialogVisible.value = true
  // 重置筛选和分页
  homeworkSearch.value = ''
  homeworkStatusFilter.value = 'all'
  homeworkSubjectFilter.value = 'all'
  homeworkCurrentPage.value = 1
}

// 打开作业详情弹窗
const openHomeworkDetailDialog = (homework) => {
  currentHomework.value = { ...homework }
  homeworkDetailDialogVisible.value = true
}

// 作业分页控制
const handleHomeworkPageSizeChange = (size) => {
  homeworkPageSize.value = size
  homeworkCurrentPage.value = 1
}

const handleHomeworkCurrentPageChange = (page) => {
  homeworkCurrentPage.value = page
}

// 作业提醒
const remindHomework = (id) => {
  const homework = allHomework.value.find(item => item.id === id)
  ElMessage({
    type: 'success',
    message: `已向${childInfo.value.name}发送作业提醒：《${homework?.title}》需在${homework?.deadline}前完成`
  })
}

// ---------------------- 通用方法 ----------------------
const tableRowClassName = ({ row }) => {
  if (row.status === '未完成' && isDeadlineNear(row.deadline)) {
    return 'warning-row'
  }
  return ''
}

const isDeadlineNear = (deadline) => {
  const today = new Date()
  const deadlineDate = new Date(deadline)
  const diffTime = deadlineDate - today
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays <= 2
}

const getSubjectTagType = (subject) => {
  const typeMap = { '语文': 'danger', '数学': 'primary', '英语': 'success', '科学': 'warning', '美术': 'info' }
  return typeMap[subject] || 'info'
}

const handleResize = () => {
  isMobile.value = window.innerWidth <= 768
}

const truncateText = (text, length = 50) => {
  if (typeof text !== 'string') return ''
  if (text.length <= length) return text
  return text.slice(0, length) + '...'
}

// 新增：格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>

<style scoped>
.parent-home-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.welcome-card {
  margin-bottom: 24px;
  border: none;
  background: linear-gradient(135deg, #f6ffed, #e6f7ff);
  border-radius: 12px;
}

.welcome-content {
  padding: 16px;
}

.welcome-content h2 {
  color: #1e293b;
  margin-bottom: 8px;
  font-size: 22px;
}

.welcome-content p {
  color: #64748b;
  margin: 0;
  font-size: 14px;
}

.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  border: none;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1) !important;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  font-size: 24px;
  margin-right: 16px;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  flex-shrink: 0;
}

.stat-data {
  flex-grow: 1;
}

.stat-title {
  color: #64748b;
  font-size: 14px;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #1e293b;
  margin-bottom: 4px;
}

.stat-unit {
  font-size: 16px;
  font-weight: normal;
  margin-left: 2px;
}

.stat-desc {
  color: #94a3b8;
  font-size: 12px;
  margin: 0;
}

.section-card {
  margin-bottom: 24px;
  border: none;
  border-radius: 12px;
}

:deep(.section-card .el-card__header) {
  border-bottom: 1px solid #f1f5f9;
  padding: 16px 20px;
  background-color: #f8fafc;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.section-title {
  margin: 0;
  font-size: 16px;
  color: #1e293b;
}

.notice-card {
  border: none;
  border-radius: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.notice-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
}

.notice-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.notice-title {
  margin: 0;
  font-size: 16px;
  color: #1e293b;
  flex-grow: 1;
}

.notice-content {
  color: #475569;
  font-size: 14px;
  margin: 8px 0;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.notice-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.notice-sender {
  color: #94a3b8;
  font-size: 12px;
}

.homework-title {
  color: #1e293b;
  text-decoration: none;
  cursor: pointer;
}

.homework-title:hover {
  color: #00B4A0;
  text-decoration: underline;
}

.deadline-near {
  color: #f56c6c;
  font-weight: 500;
}

:deep(.el-timeline) {
  padding-left: 8px;
}

:deep(.el-timeline .el-timeline-item__timestamp) {
  color: #64748b;
  font-size: 13px;
}

:deep(.el-table .warning-row) {
  --el-table-tr-bg-color: #fff8e6;
}

:deep(.el-table .warning-row:hover td) {
  background-color: #fff5d9 !important;
}

/* 通知弹窗样式（原有） */
.dialog-detail-content {
  padding: 10px 0;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.detail-title {
  margin: 0;
  font-size: 18px;
  color: #1e293b;
  font-weight: 500;
}

.detail-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 24px;
  color: #94a3b8;
  font-size: 14px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.detail-body {
  color: #475569;
  font-size: 15px;
  line-height: 1.8;
  margin-bottom: 24px;
  padding: 12px 0;
  border-top: 1px solid #f1f5f9;
  border-bottom: 1px solid #f1f5f9;
}

.read-tag {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #409eff;
}

.mark-read-btn {
  padding: 0;
  color: #409eff;
  font-size: 14px;
}

.dialog-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
  color: #94a3b8;
}

.dialog-loading p {
  margin-top: 12px;
  font-size: 14px;
}

.dialog-search-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex-grow: 1;
}

.filter-select {
  width: 160px;
}

.all-notice-item {
  border: none;
  border-radius: 8px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.all-notice-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08) !important;
  transform: translateX(2px);
}

.all-notice-header {
  margin-bottom: 8px;
}

.all-notice-title {
  margin: 0;
  font-size: 15px;
  color: #1e293b;
  display: flex;
  align-items: center;
  gap: 8px;
}

.urgent-tag {
  margin-left: 8px;
}

.unread-tag {
  margin-left: 8px;
  background-color: #e6f7ff;
  color: #409eff;
  border-color: #b3e0ff;
}

.all-notice-content {
  color: #64748b;
  font-size: 14px;
  margin: 8px 0;
  line-height: 1.6;
}

.all-notice-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  color: #94a3b8;
  font-size: 12px;
}

.all-notice-footer .el-button {
  padding: 0;
  color: #409eff;
  font-size: 13px;
}

.all-notices-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 0;
  color: #94a3b8;
}

.all-notices-empty p {
  font-size: 14px;
  margin-top: 16px;
}

.dialog-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.dialog-pagination .el-pagination) {
  --el-pagination-font-size: 13px;
}

/* ---------------------- 新增：作业弹窗样式 ---------------------- */
/* 全部作业弹窗 */
:deep(.all-homework-dialog .el-dialog__body) {
  padding: 16px 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.homework-search-bar {
  flex-wrap: wrap;
}

/* 作业统计概览 */
.homework-stats {
  margin-bottom: 8px;
}

.stats-row-mini {
  margin-bottom: 0;
}

.homework-stat-item {
  background-color: #f8fafc;
  border-radius: 8px;
  padding: 12px;
  text-align: center;
}

.stat-label {
  color: #64748b;
  font-size: 13px;
  margin-bottom: 4px;
}

.stat-count {
  font-size: 22px;
  font-weight: 700;
  color: #1e293b;
  margin-bottom: 4px;
}

.stat-tip {
  font-size: 12px;
  margin: 0;
}

.normal-tip { color: #64748b; }
.success-tip { color: #67C23A; }
.warning-tip { color: #E6A23C; }
.danger-tip { color: #F56C6C; }

/* 全部作业列表 */
.all-homework-list {
  flex-grow: 1;
}

:deep(.all-homework-list .el-table) {
  --el-table-border-color: #f1f5f9;
}

:deep(.all-homework-list .el-table th) {
  font-weight: 500;
  font-size: 13px;
}

:deep(.all-homework-list .el-table td) {
  font-size: 13px;
}

.homework-desc {
  color: #64748b;
  margin: 0;
  line-height: 1.5;
}

.operate-btn {
  padding: 0 8px;
  color: #409eff;
}

.remind-btn {
  color: #E6A23C;
}

.all-homework-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 0;
  color: #94a3b8;
}

.all-homework-empty p {
  font-size: 14px;
  margin-top: 16px;
}

/* 作业详情弹窗 */
:deep(.homework-detail-dialog .el-dialog__body) {
  padding: 20px;
}

.homework-detail-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.homework-detail-title {
  margin: 0;
  font-size: 18px;
  color: #1e293b;
  font-weight: 500;
  line-height: 1.4;
}

.subject-tag {
  margin-top: 2px;
}

.info-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 24px;
  color: #64748b;
  font-size: 14px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  white-space: nowrap;
}

.meta-label {
  color: #94a3b8;
}

.meta-value {
  color: #475569;
}

.urgent-tip {
  color: #f56c6c;
  font-size: 12px;
  margin-left: 6px;
}

.status-tag {
  margin-left: 6px;
}

.submit-time {
  margin-left: 10px;
  font-size: 12px;
  color: #94a3b8;
}

.detail-section-title {
  font-size: 16px;
  color: #1e293b;
  margin: 0 0 12px 0;
  font-weight: 500;
}

.requirement-content {
  color: #475569;
  font-size: 15px;
  line-height: 1.8;
  padding: 12px 0;
  border-top: 1px solid #f1f5f9;
  border-bottom: 1px solid #f1f5f9;
}

/* 作业附件 */
.homework-attachments, .homework-submission {
  padding: 12px 0;
  border-top: 1px solid #f1f5f9;
}

.attachment-item, .submission-file-item {
  padding: 8px 0;
  border-bottom: 1px dashed #f1f5f9;
}

.attachment-item:last-child, .submission-file-item:last-child {
  border-bottom: none;
}

.file-link {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #409eff;
  text-decoration: none;
}

.file-link:hover {
  color: #2563eb;
  text-decoration: underline;
}

.file-icon {
  font-size: 16px;
}

.file-name {
  flex-grow: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-size {
  color: #94a3b8;
  font-size: 12px;
  white-space: nowrap;
}

/* 提交情况 */
.submission-content {
  color: #475569;
  font-size: 14px;
  line-height: 1.6;
}

.submission-desc {
  margin-bottom: 12px;
}

.files-title {
  font-size: 14px;
  color: #64748b;
  margin: 0 0 8px 0;
  font-weight: 500;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .parent-home-container {
    padding: 12px;
  }
  
  .stat-content {
    padding: 16px;
  }
  
  .stat-icon {
    width: 40px;
    height: 40px;
    margin-right: 12px;
  }
  
  .stat-value {
    font-size: 24px !important;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start !important;
    gap: 8px;
  }
  
  .section-header .el-button {
    align-self: flex-end;
  }
  
  .dialog-search-bar {
    flex-direction: column;
    align-items: stretch !important;
  }
  
  .filter-select {
    width: 100%;
  }
  
  .all-notice-title {
    font-size: 14px !important;
  }
  
  .all-notice-content {
    font-size: 13px !important;
    -webkit-line-clamp: 2;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  /* 作业弹窗响应式 */
  .info-meta {
    flex-direction: column;
    align-items: flex-start !important;
    gap: 8px;
  }
  
  .homework-stat-item {
    padding: 8px;
  }
  
  .stat-count {
    font-size: 18px;
  }
  
  :deep(.all-homework-list .el-table) {
    --el-table-font-size: 12px;
  }
  
  :deep(.all-homework-list .el-table-column) {
    width: auto !important;
    min-width: 80px;
  }
}
</style>